
<template>
  <div class="blind-box-detail">
    <open-blind-box
      ref="openBlindBox"
      :poster="blindBoxInfo.poster"
      :prizeInfo="prizeInfo"
      @openBlindBox="openBlindBox"
    ></open-blind-box>
    <accep-blind-box
      ref="accepBlindBox"
      :prizeType="prizeType"
      :prizeInfo="prizeInfo"
      @acceptBlindbox="acceptBlindbox"
      @convertMoney="convertMoney"
    ></accep-blind-box>
    <dialog-custom
      ref="dialog"
      title="现金券已入袋，请尽快使用"
      confirmButtonText="我知道了"
      confirmButtonColor="#1677FF"
    ></dialog-custom>
  </div>
</template>

<script>
import store from "@/store";
import { mapGetters } from "vuex";
import apBox from "@/common/api/apBox";
import utilTool from "@/common/utils/utils";

import OpenBlindBox from "@/components/OpenBlindBox";
import AccepBlindBox from "@/components/AccepBlindBox";
import DialogCustom from "@/components/DialogCustom";

const wx = require("weixin-js-sdk");
const appId = process.env.VUE_APP_APPID;

export default {
  name: "PayBlindBox",
  props:{
    boxInfo:{
      type:Object,
      default:{}
    },
    couponInfo:{
      type:Object,
      default:{}
    },
  },
  watch:{
    boxInfo: {
      deep: true,
      immediate:true,
      handler: function (val) {
        this.blindBoxInfo = val;
      },
    },
    couponInfo: {
      deep: true,
      immediate:true,
      handler: function (val) {
        this.newCouponInfo = val;
      },
    },
  },
  components: {
    [OpenBlindBox.name]: OpenBlindBox,
    [AccepBlindBox.name]: AccepBlindBox,
    [DialogCustom.name]: DialogCustom,
  },
  data() {
    return {
      prizeInfo: {}, //奖品信息
      prizeType: "", // 获得的奖品类型  0是现金券1是商品
      prizeId: "", // 获得的奖品id
      timer: null, //定时器
      orderId: "", //订单id
      blindBoxInfo:{},
      newCouponInfo:{},
      boxId:'',
      boxUserRelation:''
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  created() {
    if (this.$route.query.boxId) {
      this.boxId = this.$route.query.boxId || "";
    }
    this.timer && clearInterval(this.timer);
  },
  mounted() {},
  methods: {
    //  展示或收起规则
    showOrHideRuleInfo() {
      this.isDown = !this.isDown;
    },
    // 开盲盒
    openBlindBox() {
      this.$toast.loading();
      apBox
        .openBox({
          id: this.boxUserRelation,
        })
        .then((data) => {
          this.openBoxSuccess(data.data);
          this.$toast.clear();
        })
        .catch(() => {});
    },
    // 打开盲盒成功
    openBoxSuccess(data) {
      console.log('打开盲盒成功')
      console.log(data)
      this.prizeInfo = data;
      this.$refs.openBlindBox.hideOverlay();
      this.$refs.accepBlindBox.showOverlay();
      this.$refs.accepBlindBox.showOverlay();
      this.$emit('openBoxSuccess',data)
    },

    // 收下盲盒
    acceptBlindbox() {
      this.timer && clearInterval(this.timer);
      this.$refs.accepBlindBox.hideOverlay();
      let prizeInfo = utilTool.deepClone(this.prizeInfo);
      this.$set(prizeInfo, "prizeName", prizeInfo.name);
      this.$set(prizeInfo, "prizePoster", prizeInfo.poster);
      this.$set(prizeInfo, "prizeType", prizeInfo.type);
      console.log('收下盲盒')
      console.log(prizeInfo)
      if (prizeInfo.prizeType === 0) {
        this.$refs.dialog.showDialog();
        this.$router.go(-1);
        return;
      }
      this.$router.replace({
        path: "/fillAddress",
        query: {
          prizeInfo: JSON.stringify(prizeInfo),
          boxId: this.boxUserRelation,
        },
      });
    },
    //  抽奖
    onDrawPrizeBtnClick() {
      // this.$refs.openBlindBox.hideOverlay();
      // this.$refs.accepBlindBox.showOverlay();
      // return
      this.$toast.loading();
      apBox
        .getPayOrderInfo({
          userId: this.userInfo.userId,
          goodsId: this.boxInfo.id,
          goodsType: 0,
          couponId:this.newCouponInfo.id
        })
        .then((data) => {
          this.$toast.clear();
          this.orderId = data.data.orderId;
          this.setPayInfo(data.data);
        });
    },
    // 设置支付信息
    setPayInfo(payInfo) {
      let that = this;
      wx.config({
        debug: false, // 这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
        appId: appId, // 必填，公众号的唯一标识
        timestamp: payInfo.timeStamp, // 必填，生成签名的时间戳
        nonceStr: payInfo.nonceStr, // 必填，生成签名的随机串
        signature: payInfo.paySign, // 必填，签名
        jsApiList: ["chooseWXPay"], // 必填，需要使用的JS接口列表
      });
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ["chooseWXPay"],
          success: function (res) {
            console.log("wx.checkJsApi:success");
            console.log(res);
          },
          fail: function (res) {
            console.log("wx.checkJsApi:fail");
            console.log(res);
          },
        });
        wx.chooseWXPay({
          timestamp: payInfo.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
          nonceStr: payInfo.nonceStr, // 支付签名随机串，不长于 32 位
          package: payInfo.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
          signType: payInfo.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
          paySign: payInfo.paySign, // 支付签名
          success: function (res) {
            that.paySuccess();
          },
          fail: function (res) {
            console.log('支付失败')
            console.log(res)
            that.$toast.err("支付失败");
          },
        });
      });
      wx.error((err) => {
        console.log('wx.error')
        console.log(err)
        that.$toast.err(err);
      });
    },
    //  支付成功
    paySuccess() {
      this.getOrderInfo();
    },
    // 获取订单信息
    getOrderInfo() {
      this.timer = setInterval(() => {
        this.$toast.loading();
        apBox
          .getOrderInfo({
            orderId: this.orderId,
          })
          .then((data) => {
            this.$toast.clear();
            this.getOrderInfoSuccess(data.data.extend);
          });
      }, 1000);
    },
    //  获取订单信息成功
    getOrderInfoSuccess(extend) {
      let tempExtend = JSON.parse(extend);
      if (tempExtend && tempExtend.boxUserRelation) {
        this.timer && clearInterval(this.timer);
        this.boxUserRelation = tempExtend.boxUserRelation;
        this.$emit('getOrderInfoSuccess',this.boxUserRelation)
        console.log('获取订单信息成功')
        console.log(this.boxUserRelation)
        this.$refs.openBlindBox.showOverlay();
      }
    },
    //  折换现金券
    convertMoney(){
      this.$emit("convertMoney");
    }
  },
};
</script>

<style lang="less" scoped>
</style>
